package cn.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import cn.dao.CategoryDao;
import cn.pojo.Category;

public class CategoryDaoImpl implements CategoryDao {
	/**
	 * 添加分类类实现
	 * @param connection
	 * @param category
	 * @throws SQLException 
	 */
	public Boolean addCategory(Connection connection,Category category) throws SQLException {
		boolean flag = false;
		String sql = "insert into category(categoryname) value(?)";
		PreparedStatement ps = connection.prepareStatement(sql);
		ps.setString(1, category.getCategoryname());
		int count = ps.executeUpdate();
		if(count!=0) {
			flag = true;
		}else {
			flag = false;
		}
		return flag;
	}
	/**
	 * 获取分类类实现
	 * @param connection
	 * @return
	 * @throws SQLException
	 */
	public List<Category> getCategory(Connection connection,int pageNo,int pageSize,String categoryname) throws SQLException{
		String sql = null;
		if("all".equals(categoryname)) {
			sql = "select * from category limit ?,?";
		}else if("allin".equals(categoryname)) {
			sql = "select * from category";
		}else {
			sql = "select * from category where categoryname like '%"+categoryname+"%' limit ?,?";
		}
		PreparedStatement ps = connection.prepareStatement(sql);
		if(!"allin".equals(categoryname)) {
			ps.setInt(1,pageNo);
			ps.setInt(2,pageSize);
		}
		
		ResultSet rs = ps.executeQuery();
		List<Category> categorys = new ArrayList<Category>();
		while(rs.next()) {
			Category category = new Category();
			category.setId(rs.getInt("id"));
			category.setCategoryname(rs.getString("categoryname"));
			category.setCreateTime(rs.getString("createtime"));
			categorys.add(category);
		}
		return categorys;
	}
	
	/**
	 * 分类删除类实现
	 * @param connection
	 * @param id
	 * @throws SQLException
	 */
	public Boolean deleteCategory(Connection connection,Integer id) throws SQLException {
		boolean flag = false;
		String sql = "delete from category where id=?";
		PreparedStatement ps = connection.prepareStatement(sql);
		ps.setInt(1, id);
		int count = ps.executeUpdate();
		if(count!=0) {
			flag = true;
		}else {
			flag = false;
		}
		return flag;
	}
	@Override
	public int getCategoryCount(Connection connection) throws SQLException {
		String sql = "select count(*) as count from category";
		Statement statement = connection.createStatement();
		ResultSet rs = statement.executeQuery(sql);
		if(rs.next()) {
			int count = rs.getInt("count");
			return count;
		}
		return 0;
	}
}
